How to avoid tons of `instanceof` in collision detection?

Posted by Prog on Game Development See other posts from Game Development or by Prog
Published on 2014-06-12T20:44:00Z Indexed on 2014/06/12 21:41 UTC
Read the original article Hit count: 134

Filed under:
|

Consider a simple game with 4 kinds of entities: Robots, Dogs, Missiles, Walls.

Here's a simple collision-detection mechanism in psuedocode: (I know, O(n^2). Irrelevant for this question).

for(Entity entityA in entities){
    for(Entity entityB in entities){
        if(collision(entityA, entityB)){
            if(entityA instanceof Robot && entityB instanceof Dog) entityB.die();
            if(entityA instanceof Robot && entityB instanceof Missile){
                entityA.die();
                entityB.die();
            }
            if(entityA instanceof Missile && entityB instanceof Wall) entityB.die();
            // .. and so on
        }
    }
}

Obviously this is very ugly, and will get bigger and harder to maintain the more entities there are, and the more conditions there are.

One option to make this better is to have separate lists for each kind of entity. For example a Robots list, a Dogs list etc. And than check for collisions of all Robots with Dogs, and all Dogs with Walls, etc.

This is better, but I still don't think it's good.

So my question is:

The collision detection system spotted a collision. Now what?

What is the common way to react to the collision? Should the system notify the entity itself that it collided with something, and have it decide for itself how to react? E.g. entityA.reactToCollision(entityB).

Or is there some other solution?

© Game Development or respective owner

Related posts about collision-detection

Related posts about oop